package com.xbongbong.paas.script.distributor.controller;


import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.menu.InitMenuHelp;
import com.xbongbong.paas.help.menu.InitOrderCenterMenuHelp;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.dto.FixDataJobDTO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.service.PaasProcessTemplateService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.ContractProductDao;
import com.xbongbong.saas.domain.entity.ContractProductEntity;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.ContractProductModel;
import com.xbongbong.sys.domain.entity.CompanyEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.CompanyModel;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;

/**
 * @author lee
 * @version v1.0
 * @date 2020/12/21 08:55
 * @since v1.0
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/script/distributor/data")
public class DistributorDataScriptController {
    private static final Logger LOG = LoggerFactory.getLogger(DistributorDataScriptController.class);

    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private CompanyModel companyModel;
    @Resource
    private InitMenuHelp initMenuHelp;
    @Resource
    private PaasProcessTemplateService paasProcessTemplateService;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private InitOrderCenterMenuHelp initOrderCenterMenuHelp;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private EsHelper esHelper;
    @Resource
    private ContractProductModel contractProductModel;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;
    @Resource
    private ContractProductDao contractProductDao;


    /**
     * 将订货单数据中的num_10的key刷掉
     * @param fixDataJobDTO
     * @param br
     * @throws XbbException
     * @author xinpeng.jiang
     * @date 2021/8/5 11:40
     * @version 1.0
     */
    @RequestMapping(value = "/repairShipmentsNumData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void repairShipmentsNumData(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        LocaleContextHolder.setLocale(Locale.CHINA);
        long start = DateTimeUtil.getInt();
        List<String> corpidList = fixDataJobDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            Map<String, Object> param = new HashMap<>();
            param.put(ParameterConstant.COLUMNS, ParameterConstant.CORPID);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put("status", BasicConstant.ONE);
            param.put("feeEndTimeGte", DateTimeUtil.getInt());
            List<CompanyEntity> companyEntityList = companyModel.findEntitys(param);
            companyEntityList.forEach(i -> corpidList.add(i.getCorpid()));
        }
        LOG.warn("数据库中共有公司{}家", corpidList.size());

        for (int i = 0; i < corpidList.size(); i++) {
            String corpid = corpidList.get(i);
            // 获取订货单表单
            int businessType = XbbRefTypeEnum.CONTRACT.getCode();
            Map<String, Object> param = new HashMap<>();
            param.put(ParameterConstant.COLUMNS, ParameterConstant.ID);
            param.put(ParameterConstant.CORPID, corpid);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put(StringConstant.BUSINESS_TYPE, businessType);
            param.put(StringConstant.DISTRIBUTOR_MARK, DistributorMarkEnum.DISTRIBUTOR.getCode());
            List<PaasFormEntityExt> paasFormEntityExtList = paasFormModel.findEntitys(param);
            // 没有直接跳过
            if (CollectionsUtil.isEmpty(paasFormEntityExtList)) {
                LOG.warn("公司{}:{}/{}", corpid, i + 1, corpidList.size());
                continue;
            }
            // es中查出所有产品
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + "." + StringConstant.KEY_WORD, corpid));
            boolQueryBuilder.filter(termQuery(ParameterConstant.FORMID, paasFormEntityExtList.get(0).getId()));
            List<PaasFormDataEntity> paasFormDataEntityList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT, boolQueryBuilder, PaasFormDataEntity.class, null);
            if (CollectionsUtil.isEmpty(paasFormDataEntityList)) {
                LOG.warn("公司{}:{}/{}", corpid, i + 1, corpidList.size());
                continue;
            }
            boolean needUpdate = false;
            List<ContractProductEntity> contractProductEntityList = transferSubFormHelper.transferFormDataToContractProductList(paasFormDataEntityList);
            for (ContractProductEntity contractProductEntity : contractProductEntityList) {
                JSONObject data = contractProductEntity.getData();
                if (Objects.isNull(data)) {
                    continue;
                }
                if (data.containsKey("num_10")) {
                    needUpdate = true;
                    data.put("num_10", null);
                    contractProductEntity.setData(data);
                    contractProductEntity.setUpdateTime(DateTimeUtil.getInt());
                }
            }
            // 更新
            if (needUpdate) {
                contractProductDao.updateBatch4Data(contractProductEntityList, corpid);;
            }
            LOG.warn("公司{}:{}/{}", corpid, i + 1, corpidList.size());
        }
        LOG.warn("consume:{}s", (DateTimeUtil.getInt() - start));
        LOG.warn("操作成功");
    }

    /**
     * 将订货单数据中的text_19的key刷掉
     * @param fixDataJobDTO
     * @param br
     * @throws XbbException
     * @author xinpeng.jiang
     * @date 2021/8/5 11:40
     * @version 1.0
     */
    @RequestMapping(value = "/repairPromotionData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void repairPromotionData(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        LocaleContextHolder.setLocale(Locale.CHINA);
        long start = DateTimeUtil.getInt();
        List<String> corpidList = fixDataJobDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            Map<String, Object> param = new HashMap<>();
            param.put(ParameterConstant.COLUMNS, ParameterConstant.CORPID);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put("status", BasicConstant.ONE);
            param.put("feeEndTimeGte", DateTimeUtil.getInt());
            List<CompanyEntity> companyEntityList = companyModel.findEntitys(param);
            companyEntityList.forEach(i -> corpidList.add(i.getCorpid()));
        }
        LOG.warn("数据库中共有公司{}家", corpidList.size());

        for (int i = 0; i < corpidList.size(); i++) {
            String corpid = corpidList.get(i);
            // 获取订货单表单
            int businessType = XbbRefTypeEnum.CONTRACT.getCode();
            Map<String, Object> param = new HashMap<>();
            param.put(ParameterConstant.COLUMNS, ParameterConstant.ID);
            param.put(ParameterConstant.CORPID, corpid);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put(StringConstant.BUSINESS_TYPE, businessType);
            param.put(StringConstant.DISTRIBUTOR_MARK, DistributorMarkEnum.DISTRIBUTOR.getCode());
            List<PaasFormEntityExt> paasFormEntityExtList = paasFormModel.findEntitys(param);
            // 没有直接跳过
            if (CollectionsUtil.isEmpty(paasFormEntityExtList)) {
                LOG.warn("公司{}:{}/{}", corpid, i + 1, corpidList.size());
                continue;
            }
            // es中查出所有产品
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + "." + StringConstant.KEY_WORD, corpid));
            boolQueryBuilder.filter(termQuery(ParameterConstant.FORMID, paasFormEntityExtList.get(0).getId()));
            List<PaasFormDataEntity> paasFormDataEntityList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT, boolQueryBuilder, PaasFormDataEntity.class, null);
            if (CollectionsUtil.isEmpty(paasFormDataEntityList)) {
                LOG.warn("公司{}:{}/{}", corpid, i + 1, corpidList.size());
                continue;
            }
            boolean needUpdate = false;
            List<ContractProductEntity> contractProductEntityList = transferSubFormHelper.transferFormDataToContractProductList(paasFormDataEntityList);
            for (ContractProductEntity contractProductEntity : contractProductEntityList) {
                JSONObject data = contractProductEntity.getData();
                if (Objects.isNull(data)) {
                    continue;
                }
                if (data.containsKey("text_19")) {
                    needUpdate = true;
                    data.put("text_21", data.get("text_19"));
                    data.put("text_19", null);
                    contractProductEntity.setData(data);
                    contractProductEntity.setUpdateTime(DateTimeUtil.getInt());
                }
            }
            // 更新
            if (needUpdate) {
                contractProductDao.updateBatch4Data(contractProductEntityList, corpid);
            }
            LOG.warn("公司{}:{}/{}", corpid, i + 1, corpidList.size());
        }
        LOG.warn("consume:{}s", (DateTimeUtil.getInt() - start));
        LOG.warn("操作成功");
    }
}
